// import { PageMode, PaperDirection } from '../../editor'
import { OptionPanel } from '../../components/option-panel/OptionPanel'
import { Dialog } from '../../components/dialog/Dialog'
import { createApp } from 'vue'
import { PaperDirection, PageMode } from '../../editor/dataset/enum/Editor'
import type { IEditorOption } from '../../editor/interface/Editor'

/**
 * 初始化页面设置相关功能
 * @param editor 编辑器实例
 */
export default function initPageSettings(editor: any): void {
  // 编辑器选项配置
  const editorOptionDom = document.querySelector<HTMLDivElement>('.editor-option')!

  editorOptionDom.onclick = function () {
    const options = editor.command.getOptions()
    new OptionPanel({
      title: '编辑器配置',
      data: options,
      onConfirm: (newOption: Partial<IEditorOption>) => {
        editor.command.executeUpdateOptions(newOption)
      }
    })
  }
  // 页面设置按钮通过Vue组件实现
  const pageSettingsDom = document.querySelector<HTMLDivElement>('.editor-option2')
  if (pageSettingsDom) {
    pageSettingsDom.onclick = function () {
      // 动态加载并显示PageSettingsPanel组件
      import('../../components/option-panel/PageSettingsPanel.vue')
        .then(({ default: PageSettingsPanel }) => {
          // 创建一个临时容器
          const container = document.createElement('div')
          container.style.position = 'fixed'
          container.style.top = '0'
          container.style.left = '0'
          container.style.width = '100%'
          container.style.height = '100%'
          container.style.zIndex = '1000'
          document.body.appendChild(container)

          // 获取当前编辑器选项
          const options = editor.command.getOptions()
          // 创建Vue应用实例并挂载组件
          const app = createApp(PageSettingsPanel, {
            title: '页面设置',
            data: options,
            onConfirm: (newOption: Partial<IEditorOption>) => {
              // 应用新的设置
              editor.command.executeUpdateOptions(newOption)
              // 清理并移除组件
              app.unmount()
              document.body.removeChild(container)
            },
            onClose: () => {
              // 清理并移除组件
              app.unmount()
              document.body.removeChild(container)
            }
          })
          app.mount(container)
        })
        .catch(err => {
          console.error('Failed to load PageSettingsPanel component:', err)
        })
    }
  }

  // 目录显隐
  let isCatalogShow = true
  const catalogDom = document.querySelector<HTMLElement>('.catalog')!
  const catalogModeDom = document.querySelector<HTMLDivElement>('.catalog-mode')!
  const catalogHeaderCloseDom = document.querySelector<HTMLDivElement>('.catalog__header__close')!

  async function updateCatalog() {
    const catalog = await editor.command.getCatalog()
    const catalogMainDom = document.querySelector<HTMLDivElement>('.catalog__main')!
    catalogMainDom.innerHTML = ''
    if (catalog) {
      const appendCatalog = (parent: HTMLDivElement, catalogItems: any[]) => {
        for (let c = 0; c < catalogItems.length; c++) {
          const catalogItem = catalogItems[c]
          const catalogItemDom = document.createElement('div')
          catalogItemDom.classList.add('catalog-item')
          // 渲染
          const catalogItemContentDom = document.createElement('div')
          catalogItemContentDom.classList.add('catalog-item__content')
          const catalogItemContentSpanDom = document.createElement('span')
          catalogItemContentSpanDom.innerText = catalogItem.name
          catalogItemContentDom.append(catalogItemContentSpanDom)
          // 定位
          catalogItemContentDom.onclick = () => {
            editor.command.executeLocationCatalog(catalogItem.id)
          }
          catalogItemDom.append(catalogItemContentDom)
          if (catalogItem.subCatalog && catalogItem.subCatalog.length) {
            appendCatalog(catalogItemDom, catalogItem.subCatalog)
          }
          // 追加
          parent.append(catalogItemDom)
        }
      }
      appendCatalog(catalogMainDom, catalog)
    }
  }

  const switchCatalog = () => {
    isCatalogShow = !isCatalogShow
    if (isCatalogShow) {
      catalogDom.style.display = 'block'
      updateCatalog()
    } else {
      catalogDom.style.display = 'none'
    }
  }

  catalogModeDom.onclick = switchCatalog
  catalogHeaderCloseDom.onclick = switchCatalog

  // 页面模式
  // const pageModeDom = document.querySelector<HTMLDivElement>('.page-mode')!

  // const pageModeOptionsDom =
  //   pageModeDom.querySelector<HTMLDivElement>('.options')!

  // // 已经在Footer.vue中实现了点击显示/隐藏选项的逻辑，这里只处理选项点击事件
  // // 移除重复的点击显示/隐藏逻辑，避免覆盖Footer.vue中的实现

  // pageModeOptionsDom.onclick = function (evt) {
  //   const li = evt.target as HTMLLIElement
  //   editor.command.executePageMode(<PageMode>li.dataset.pageMode!)
  // }

  // 页面模式
  const pageModeDom = document.querySelector<HTMLDivElement>('.page-mode')!
  const pageModeOptionsDom = pageModeDom.querySelector<HTMLDivElement>('.options')!

  pageModeDom.onclick = function () {
    pageModeOptionsDom.classList.toggle('visible')
  }

  pageModeOptionsDom.onclick = function (evt) {
    const li = evt.target as HTMLLIElement
    editor.command.executePageMode(<PageMode>li.dataset.pageMode!)
  }

  // 页面缩放
  document.querySelector<HTMLDivElement>('.page-scale-percentage')!.onclick = function () {
    console.log('page-scale-recovery')
    editor.command.executePageScaleRecovery()
  }

  document.querySelector<HTMLDivElement>('.page-scale-minus')!.onclick = function () {
    console.log('page-scale-minus')
    editor.command.executePageScaleMinus()
  }

  document.querySelector<HTMLDivElement>('.page-scale-add')!.onclick = function () {
    console.log('page-scale-add')
    editor.command.executePageScaleAdd()
  }

  // // 纸张大小
  const paperSizeDom = document.querySelector<HTMLDivElement>('.paper-size')!
  const paperSizeDomOptionsDom = paperSizeDom.querySelector<HTMLDivElement>('.options')!

  paperSizeDom.onclick = function () {
    paperSizeDomOptionsDom.classList.toggle('visible')
  }

  paperSizeDomOptionsDom.onclick = function (evt) {
    const li = evt.target as HTMLLIElement
    const paperType = li.dataset.paperSize!
    const [width, height] = paperType.split('*').map(Number)

    editor.command.executePaperSize(width, height)
    // 纸张状态回显
    paperSizeDomOptionsDom.querySelectorAll('li').forEach(child => child.classList.remove('active'))
    li.classList.add('active')
  }

  //纸张方向
  const paperDirectionDom = document.querySelector<HTMLDivElement>('.paper-direction')!
  const paperDirectionDomOptionsDom = paperDirectionDom.querySelector<HTMLDivElement>('.options')!

  paperDirectionDom.onclick = function () {
    paperDirectionDomOptionsDom.classList.toggle('visible')
  }

  paperDirectionDomOptionsDom.onclick = function (evt) {
    const li = evt.target as HTMLLIElement
    const paperDirection = li.dataset.paperDirection!
    editor.command.executePaperDirection(<PaperDirection>paperDirection)
    // 纸张方向状态回显
    paperDirectionDomOptionsDom.querySelectorAll('li').forEach(child => child.classList.remove('active'))
    li.classList.add('active')
  }

  // 页面边距
  const paperMarginDom = document.querySelector<HTMLDivElement>('.paper-margin')!

  paperMarginDom.onclick = function () {
    const [topMargin, rightMargin, bottomMargin, leftMargin] = editor.command.getPaperMargin()
    new Dialog({
      title: '页边距',
      data: [
        {
          type: 'text',
          label: '上边距',
          name: 'top',
          required: true,
          value: `${topMargin}`,
          placeholder: '请输入上边距'
        },
        {
          type: 'text',
          label: '下边距',
          name: 'bottom',
          required: true,
          value: `${bottomMargin}`,
          placeholder: '请输入下边距'
        },
        {
          type: 'text',
          label: '左边距',
          name: 'left',
          required: true,
          value: `${leftMargin}`,
          placeholder: '请输入左边距'
        },
        {
          type: 'text',
          label: '右边距',
          name: 'right',
          required: true,
          value: `${rightMargin}`,
          placeholder: '请输入右边距'
        }
      ],
      onConfirm: payload => {
        const top = payload.find(p => p.name === 'top')?.value
        if (!top) return
        const bottom = payload.find(p => p.name === 'bottom')?.value
        if (!bottom) return
        const left = payload.find(p => p.name === 'left')?.value
        if (!left) return
        const right = payload.find(p => p.name === 'right')?.value
        if (!right) return
        editor.command.executeSetPaperMargin([Number(top), Number(right), Number(bottom), Number(left)])
      }
    })
  }

  // 全屏
  const fullscreenDom = document.querySelector<HTMLDivElement>('.fullscreen')!

  fullscreenDom.onclick = toggleFullscreen
  window.addEventListener('keydown', evt => {
    if (evt.key === 'F11') {
      toggleFullscreen()
      evt.preventDefault()
    }
  })

  document.addEventListener('fullscreenchange', () => {
    fullscreenDom.classList.toggle('exist')
  })

  function toggleFullscreen() {
    console.log('fullscreen')
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen()
    } else {
      document.exitFullscreen()
    }
  }
}
